package com.bkhc.umc.repository;

import com.bkhc.common.vo.UserRoleVo;
import com.bkhc.umc.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User,String> , JpaSpecificationExecutor<User> {

    default Page<User> findAll(User user, Pageable pageable){
     return findAll(new Specification<User>() {
         @Override
         public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
             List<Predicate> predicate = new ArrayList<>();
             if(!StringUtils.isEmpty(user.getEmail())){
                 predicate.add(criteriaBuilder.like(root.get("email").as(String.class),"%"+user.getEmail()+"%"));
             }
             if(!StringUtils.isEmpty(user.getUsername())){
                 predicate.add(criteriaBuilder.like(root.get("username").as(String.class),"%"+user.getUsername()+"%"));
             }

             if(!StringUtils.isEmpty(user.getFullName())){
                 predicate.add(criteriaBuilder.like(root.get("fullName").as(String.class),"%"+user.getFullName()+"%"));
             }
             if(!StringUtils.isEmpty(user.getStatus())){
                 predicate.add(criteriaBuilder.equal(root.get("status").as(String.class),user.getStatus()));
             }
             Predicate[] pre = new Predicate[predicate.size()];

             return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
         }
     },pageable);


    };
    @Query("SELECT  COUNT(u.username) FROM  User u WHERE u.username=?1 or u.phone=?2 or u.email=?3")
    int find(String username, String phone, String email);

    User findByUserId(String userId);

    @Query("select u,r.roleName from UserRole u left join Role r on u.roleCode=r.roleCode where u.userId=?1")
    List<UserRoleVo> findUserRoleByUserId(String userId);

    User findByUsername(String username);
}
